package com.coolxiaoyao.common.context;

import com.coolxiaoyao.common.core.IContainerInitializer;
import com.coolxiaoyao.common.handler.AnnotationHandler;
import com.coolxiaoyao.common.http.ExceptionHandler;
import com.coolxiaoyao.common.http.HttpMethod;
import com.coolxiaoyao.common.inner.UrlInnerExchange;
import com.coolxiaoyao.common.mapping.UrlMapping;

import java.util.Map;

/**
 * @author Kerry on 18/09/20
 */

public abstract class AbstractNtApplicationContext implements IContainerInitializer {

    protected Map<String, Map<HttpMethod, UrlMapping>> urlMapping;
    /**
     * 默认异常处理器
     */
    protected ExceptionHandler exceptionHandler;


    @Override
    public void startup(String... packageNames) throws Exception {
        beforeContainerInit(null, packageNames);
        this.urlMapping = AnnotationHandler.scannerByPackage(packageNames);
        afterContainerInit(null, packageNames);
    }

    @Override
    public void startup(String[] args, boolean isPackage, Class<?>... primaryClass) throws Exception {
        beforeContainerInit(args, primaryClass);
        if (isPackage) {
            String[] packageNames = new String[primaryClass.length];
            for (int i = 0; i < primaryClass.length; i++) {
                packageNames[i] = primaryClass[i].getPackage().getName();
            }
            this.urlMapping = AnnotationHandler.scannerByPackage(packageNames);
        } else {
            this.urlMapping = AnnotationHandler.scannerByClass(primaryClass);
        }
        afterContainerInit(args, primaryClass);
    }

    /**
     * 开启之前
     *
     * @param args
     * @param primaryClass
     */
    protected abstract void beforeContainerInit(String[] args, Object[] primaryClass);

    /**
     * 开启之后
     *
     * @param args
     * @param primaryClass
     */
    protected abstract void afterContainerInit(String[] args, Object[] primaryClass);

    /**
     * 匹配URL
     *
     * @param url
     * @return
     */
    public abstract UrlInnerExchange matchUrlMapping(String url);


    public void setExceptionHandler(ExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    public ExceptionHandler getExceptionHandler() {

        return exceptionHandler;
    }

    public Map<String, Map<HttpMethod, UrlMapping>> getUrlMapping() {
        return urlMapping;
    }

    public void setUrlMapping(Map<String, Map<HttpMethod, UrlMapping>> urlMapping) {
        this.urlMapping = urlMapping;
    }
}
